<template>
  <div class="shuati-all">
    <div class="shuati-container">
      <div class="select-row">
        <span class="cascader-title">课程</span>
        <el-cascader
          v-model="selectedId"
          size="large"
          :options="table"
          :props="props1"
          clearable
          placeholder="请选择科目"
          @change="handleChange"
        ></el-cascader>
      </div>
      <el-input
        style="margin-top: 10px; width: 99%"
        v-model="input"
        placeholder="请输入题目内容，支持模糊搜索"
        size="large"
        :prefix-icon="Search"
        @keyup.enter="handleSearch"
      >
        <template #append>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </template>
      </el-input>
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="subject" width="150px" label="课程">
        <template #default="scope">
          {{ getSubjectName(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column prop="question" label="题目" />
      <el-table-column prop="answer" label="答案">
        <template #default="scope">
          <span v-html="formatAnswer(scope.row)"></span>
        </template>
      </el-table-column>
      <el-table-column prop="remark" label="解析" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button
            size="small"
            type="primary"
            text
            @click="handleEdit(scope.row)"
            >查看</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="prev, pager, next"
      :page-count="pageCount"
      :current-page="currentPage"
      @current-change="handleCurrentChange"
    />
    <el-dialog v-model="dialogVisible" title="题目详情" width="60%">
      <el-card v-if="currentQuestion" class="question-card">
        <div class="question-content">
          <h3>题目</h3>
          <p>{{ currentQuestion.question }}</p>

          <h3>选项</h3>
          <el-checkbox-group v-model="selectedAnswers" disabled>
            <div v-if="currentQuestion.item1" class="option-item">
              <el-checkbox :value="'A'">{{
                currentQuestion.item1
              }}</el-checkbox>
            </div>
            <div v-if="currentQuestion.item2" class="option-item">
              <el-checkbox :value="'B'">{{
                currentQuestion.item2
              }}</el-checkbox>
            </div>
            <div v-if="currentQuestion.item3" class="option-item">
              <el-checkbox :value="'C'">{{
                currentQuestion.item3
              }}</el-checkbox>
            </div>
            <div v-if="currentQuestion.item4" class="option-item">
              <el-checkbox :value="'D'">{{
                currentQuestion.item4
              }}</el-checkbox>
            </div>
          </el-checkbox-group>

          <h3>答案</h3>
          <p>{{ currentQuestion.answer }}</p>

          <template v-if="currentQuestion.remark">
            <h3>解析</h3>
            <p>{{ currentQuestion.remark }}</p>
          </template>
        </div>
      </el-card>
    </el-dialog>
  </div>
</template>

<script setup>
import subjectApi from "@/api/subject/index";
import { onMounted, ref, computed } from "vue";
import { Search } from "@element-plus/icons-vue";
import lastRecord from "@/api/record/lastRecord";
import questionApi from "@/api/question/index";
import { useStore } from "vuex";
import { getToken } from "@/utils/auth"; // get token from cookie
import { number } from "echarts";

const store = useStore();

const props1 = {
  checkStrictly: true,
};

const tableData = ref([]);
const table = ref([]);
const input = ref("");
const currentPage = ref(1);
const pageCount = ref(0);

const getSubject = async () => {
  const res = await subjectApi.getTree();
  table.value = res.data;
};

const selectedId = ref(null);
let selectValue = "";
const dialogVisible = ref(false);
const currentQuestion = ref(null);
const selectedAnswers = ref([]);

const findNodeById = (nodes, targetId) => {
  for (const node of nodes) {
    if (node.value === targetId) {
      return node;
    }
    if (node.children && node.children.length > 0) {
      const found = findNodeById(node.children, targetId);
      if (found) return found;
    }
  }
  return null;
};

const getSubjectName = (data) => {
  const node = findNodeById(table.value, data.subjectId);
  return node.label;
};

const handleEdit = (row) => {
  currentQuestion.value = row;
  selectedAnswers.value = row.answer.split("+");
  dialogVisible.value = true;
};

const findNodeByValue = (nodes, targetValue) => {
  for (const node of nodes) {
    if (node.value === targetValue) {
      return node;
    }
    if (node.children) {
      const found = findNodeByValue(node.children, targetValue);
      if (found) return found;
    }
  }
  return null;
};

const handleChange = async (value) => {
  // 遍历选中的路径找到最后一个节点
  let label = "";
  let currentNode = null;
  for (let i = 0; i < value.length; i++) {
    const element = value[i];
    currentNode = findNodeByValue(table.value, element);
    if (!label) {
      label = currentNode.label;
    } else {
      label = label + "/" + currentNode.label;
    }
  }

  const id = value[value.length - 1];

  // 获取指定节点下的所有叶子节点ID

  // 获取所有叶子节点的ID
  const leafNodeIds = getLeafNodeIds(table.value, id);

  const res = await questionApi.listBySubject(
    input.value,
    leafNodeIds,
    currentPage.value,
    10
  );
  tableData.value = res.data;
  const res2 = await questionApi.totalBySubject(input.value, leafNodeIds);
  pageCount.value = Math.ceil(res2.data / 10);

  // 更新选中值的标签
  selectValue = label;

  await lastRecord.addOrUpdate(id, selectValue);
  //把选中的课程和课程ID存放到store中
  store.dispatch("learn/setSelectValue", selectValue);
  store.dispatch("learn/setSelectedId", id);
};

const getLeafNodeIds = (nodes, targetId) => {
  const leafIds = [];

  const findLeafNodes = (node) => {
    if (!node.children || node.children.length === 0) {
      leafIds.push(node.value); // 假设节点的ID存储在value字段中
      return;
    }
    node.children.forEach((child) => findLeafNodes(child));
  };

  // 先找到目标节点
  const targetNode = findNodeByValue(nodes, targetId);
  if (targetNode) {
    findLeafNodes(targetNode);
  }

  return leafIds;
};

const getQuestion = async () => {
  let leafNodeIds = getLeafNodeIds(table.value, selectedId.value);
  const res = await questionApi.listBySubject(
    input.value,
    leafNodeIds,
    currentPage.value,
    10
  );
  tableData.value = res.data;
  const res2 = await questionApi.totalBySubject(input.value, leafNodeIds);
  pageCount.value = Math.ceil(res2.data / 10);
};

const handleCurrentChange = async (page) => {
  currentPage.value = page;
  await getQuestion();
};

const handleSearch = async () => {
  let id = null;
  //如果typeof selectedId.values 是数字
  if (typeof selectedId.value === "number") {
    id = selectedId.value;
  } else {
    id = selectedId.value[selectedId.value.length - 1];
  }
  // 获取所有叶子节点的ID
  const leafNodeIds = getLeafNodeIds(table.value, id);

  const res = await questionApi.listBySubject(
    input.value,
    leafNodeIds,
    currentPage.value,
    10
  );
  tableData.value = res.data;
  const res2 = await questionApi.totalBySubject(input.value, leafNodeIds);
  pageCount.value = Math.ceil(res2.data / 10);
};

// 添加格式化答案的方法
const formatAnswer = (data) => {
  switch (data.answer) {
    case "A":
      return data.item1;
    case "B":
      return data.item2;
    case "C":
      return data.item3;
    case "D":
      return data.item4;
    default:
      let str = "";
      const arr = data.answer.split("+");
      for (let i = 0; i < arr.length; i++) {
        switch (arr[i]) {
          case "A":
            str += data.item1;
            break;
          case "B":
            str += data.item2;
            break;
          case "C":
            str += data.item3;
            break;
          case "D":
            str += data.item4;
            break;
        }
        if (i < arr.length - 1) {
          str += "<br>";
        }
      }
      return str;
  }
};

const getLastRecord = async () => {
  if (!store.getters.selectValue || !store.getters.selectedId) {
    const res = await lastRecord.getLastRecord();
    if (res.data) {
      selectValue = res.data.chatperName;
      selectedId.value = res.data.selectedId;
      store.dispatch("learn/setSelectValue", selectValue);
      store.dispatch("learn/setSelectedId", selectedId.value);
    }
  } else {
    selectValue = store.getters.selectValue;
    selectedId.value = store.getters.selectedId;
  }
};

onMounted(async () => {
  if (getToken()) {
    await getSubject();
    await getLastRecord();
    await getQuestion();
  }
});
</script>

<style scoped>
.shuati-all {
  padding: 10px 0;
  background-color: #f5f5f5;
}

.shuati-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 0 auto;
  padding-top: 10px;
  border: 1px solid #e6e1e1;
  border-radius: 2px;
  margin-top: 10px;
  padding-bottom: 10px;
  background-color: white;
}

img {
  height: 12vh;
}

.learning-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  cursor: pointer;
}

.learning-item:hover {
  background-color: #f5f5f5;
  color: #333333;
}

.learning-item:hover span {
  color: rgb(0, 174, 255);
}

.select-row {
  display: flex;
  align-items: center;
  gap: 20px;
  width: 100%;
}

.cascader-title {
  margin-left: 1%;
  margin-bottom: 0;
  color: #333;
}

.question-card {
  margin: 10px;
}

.question-content {
  padding: 10px;
}

.question-content h3 {
  color: #333;
  margin: 15px 0 10px 0;
}

.option-item {
  margin: 10px 0;
}

.answer-cell {
  white-space: pre-line;
  display: block;
}
</style>
